package com.bw.demo_mvvm.net

import androidx.lifecycle.LiveData
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/16 19:15
 * @Description :
 */
class LiveDataCallAdapter<T>(var responseType: Type): CallAdapter<T, LiveData<T>> {
    override fun responseType(): Type {
        return responseType
    }

    override fun adapt(call: Call<T>): LiveData<T> {
        return object: LiveData<T>(){
            var start = AtomicBoolean(false)
            override fun onActive() {
                super.onActive()
                if (start.compareAndSet(false, true)){
                    call.enqueue(object : Callback<T>{
                        override fun onResponse(call: Call<T>, response: Response<T>) {
                            if (response.code() == 200){
                                postValue(response.body())
                            }else{
                                postValue(BaseResponse(response.code(), "", response.message()) as T)
                            }
                        }

                        override fun onFailure(call: Call<T>, t: Throwable) {
                            postValue(BaseResponse(404, "", t.message.toString()) as T)
                        }
                    })
                }
            }
        }
    }
}